<template>
  <div class="content">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="字典名">
        <el-input v-model="formInline.name" placeholder="请输入字典名" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <el-button @click="dialogVisible = true" plain type="primary">新增</el-button>
        <el-button @click="init">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableParmas.rows">
      <el-table-column prop="name" label="字典名"></el-table-column>
      <el-table-column label="字典编码" prop="code">
        <template #default="scope">
          <el-button type="primary" @click="showDetais(scope.row)" text>{{ scope.row.code }}</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注"></el-table-column>
      <el-table-column label="创建时间" align="center" width="160" prop="createTime">
        <template #default="scope">
          <span>{{ proxy.$utils.dateTimeFormateFn(scope.row._add_time, "all") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleClick(scope.row, 1)">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleClick(scope.row, 2)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <Pagination v-if="tableParmas['total']" :total="tableParmas['total']" v-model:page="formInline.pageIndex" v-model:limit="formInline.pageSize" @pagination="getInfo" />

    <el-dialog v-model="dialogVisible" title="字典新增/编辑" width="500" :before-close="handleClose">
      <el-form :model="params" ref="menuRef" :rules="rules" label-width="100px">
        <el-form-item label="字典名" prop="name">
          <el-input v-model="params.name" placeholder="请输入字典名" clearable />
        </el-form-item>
        <el-form-item label="字典编码" prop="code">
          <el-input v-model="params.code" placeholder="请输入字典编码" clearable />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="params.remark" placeholder="请输入备注" type="textarea" :autosize="{ minRows: 4 }" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="loading">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="show" title="字典值" width="1000" :before-close="handleClose">
      <div class="actionBtn">
        <el-button type="primary" @click="add">新增</el-button>
      </div>
      <el-table :data="info.data ? info.data : []" class="dict-table">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="name" label="字典标签">
          <template #default="scope">
            <el-input v-model="scope.row.dict_label" placeholder="请输入字典标签" />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="字典键值">
          <template #default="scope">
            <el-input v-model="scope.row.dict_code" placeholder="请输入字典键值" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center">
          <template #default="scope">
            <span>{{ proxy.$utils.dateTimeFormateFn(scope.row._add_time, "all") }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150" fixed="right">
          <template #default="scope">
            <el-button link type="primary" icon="Delete" @click="info.data.splice(scope.$index, 1)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="toSubmit" :loading="loading">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
const { proxy } = getCurrentInstance();

let formInline = ref({
  name: "",
  code: "",
  pageIndex: 1,
  pageSize: 10,
});
let tableParmas = ref({});
let params = ref({
  _id: "",
  name: "",
  code: "",
  remark: "",
});
let info = ref({});
let dialogVisible = ref(false);
let loading = ref(false);
let show = ref(false);
let rules = ref({
  name: [{ required: true, message: "请输入字典名", trigger: "blur" }],
  code: [{ required: true, message: "请输入字典编码", trigger: "blur" }],
});

onMounted(() => {
  const jsonArray = [
    { id: 1, name: "Alice" },
    { id: 2, name: "Bob" },
    { id: 3, name: "Charlie" },
    { id: 4, name: "Alice" },
  ];
  let resp = proxy.$utils.findDuplicatesByField(jsonArray, "name");
  console.log("重复", resp);
  getInfo();
});

function init() {
  formInline.value = {
    name: "",
    code: "",
    pageIndex: 1,
    pageSize: 10,
  };
  getInfo();
}

let onSubmit = () => {
  formInline.value.pageIndex = 1;
  getInfo();
};

let submitForm = () => {
  proxy.$refs["menuRef"].validate((valid) => {
    if (valid) {
      save();
    }
  });
};
let save = async () => {
  try {
    loading.value = true;
    let query = {
      type: "add",
      data: params.value,
    };
    if (params.value._id) query["type"] = "update";
    await proxy.$apis.dict(query);
    proxy.$utils.showToast("操作成功");
    handleClose();
  } catch (error) {
  } finally {
    loading.value = false;
  }
};

let getInfo = async () => {
  tableParmas.value = await proxy.$apis.dict({
    type: "list",
    data: formInline.value,
  });
  console.log("字典", tableParmas.value);
};
let handleClose = () => {
  params.value = {
    _id: "",
    name: "",
    code: "",
    remark: "",
  };
  info.value = {};
  dialogVisible.value = false;
  getInfo();
  show.value = false;
};

let handleClick = async (row, num) => {
  switch (num) {
    case 1:
      params.value = proxy.$utils.formatFunction(row, { ...params.value });
      dialogVisible.value = true;
      break;
    case 2:
      let resp = await proxy.$utils.confirmTips("确认删除?");
      if (!resp) return;
      await proxy.$apis.dict({
        type: "delete",
        data: { _id: row._id },
      });
      proxy.$utils.showToast("操作成功");
      getInfo();
      break;
    default:
      break;
  }
};

let showDetais = (row) => {
  info.value = row;
  if (!info.value.hasOwnProperty("data")) info.value.data = [];
  show.value = true;
};
let add = () => {
  let resp = proxy.$utils.findDuplicatesByField(info.value.data, "dict_code");
  console.log("重复", resp);
  if (resp && resp.length)
    return proxy.$utils.showToast(`${resp[0].dict_label}字典值重复`, 0);
  info.value.data.push({
    dict_label: "",
    dict_code: "",
    remark: "",
    _add_time: new Date().getTime(),
  });
};
let toSubmit = async () => {
  try {
    loading.value = true;
    let data = [...info.value.data];
    let resp = proxy.$utils.findDuplicatesByField(data, "dict_code");
    if (resp && resp.length)
      return proxy.$utils.showToast(`${resp[0].dict_label}字典值重复`, 0);
    for (let index = 0; index < data.length; index++) {
      const element = data[index];
      if (element.dict_label === "" || element.dict_code === "") {
        return proxy.$utils.showToast("字典标签和字典键值不能为空");
      }
    }
    await proxy.$apis.dict({
      type: "update",
      data: info.value,
    });
    proxy.$utils.showToast("操作成功");
    handleClose();
  } catch (error) {
  } finally {
    loading.value = false;
  }
};
</script>

<style lang="scss" scoped>
.content {
  margin: 20px;
}
.dict-table {
  max-height: 60vh;
  overflow-y: auto;
}
.actionBtn {
  margin-bottom: 15px;
}
</style>
